import { defineStore } from 'pinia'
import { ref } from 'vue'
import service from '../config'
import { ElMessage } from 'element-plus'

// 文章分类数据类型
interface ArticleCategory {
    id: number
    name: string
    parentId: number | null
    alias: string
}

// 语言分类数据类型
interface LanguageCategory {
    id: number
    name: string
    [key: string]: any
}

// 树形结构数据类型
interface TreeNode {
    label: string
    value: number
    parentId: number | null
    alias: string
    children?: TreeNode[]
}

export const useCommonStore = defineStore('common', () => {
    // 文章分类数据
    const articleCategories = ref<TreeNode[]>([])
    const articleCategoriesLoading = ref(false)
    const articleCategoriesLoaded = ref(false)

    // 语言分类数据
    const languageCategories = ref<LanguageCategory[]>([])
    const languageCategoriesLoading = ref(false)
    const languageCategoriesLoaded = ref(false)

    // 构建树形结构的通用函数
    const buildTree = (nodes: ArticleCategory[], parentId: number | null = null): TreeNode[] => {
        return nodes
            .filter(node => node.parentId === parentId)
            .map(node => {
                const children = buildTree(nodes, node.id);
                return {
                    label: node.name,
                    value: node.id,
                    parentId: node.parentId,
                    alias: node.alias,
                    ...(children.length > 0 ? { children } : {})
                };
            });
    }

    // 获取文章分类数据
    const getArticleCategories = async (forceRefresh = false): Promise<TreeNode[]> => {
        // 如果已经加载过且不强制刷新，直接返回缓存数据
        if (articleCategoriesLoaded.value && !forceRefresh) {
            return articleCategories.value
        }

        // 如果正在加载中，等待加载完成
        if (articleCategoriesLoading.value) {
            return new Promise((resolve) => {
                const checkLoaded = () => {
                    if (articleCategoriesLoaded.value) {
                        resolve(articleCategories.value)
                    } else {
                        setTimeout(checkLoaded, 100)
                    }
                }
                checkLoaded()
            })
        }

        articleCategoriesLoading.value = true

        try {
            const response = await service.get('/article/allCategory')
            const treeData = response.data?.map((item: ArticleCategory) => ({
                id: item.id,
                name: item.name,
                parentId: item.parentId,
                alias: item.alias
            })) || []

            articleCategories.value = buildTree(treeData)
            articleCategoriesLoaded.value = true
            return articleCategories.value
        } catch (error) {
            console.error('Error fetching article categories:', error)
            ElMessage.error('获取文章分类失败')
            return []
        } finally {
            articleCategoriesLoading.value = false
        }
    }

    // 获取语言分类数据
    const getLanguageCategories = async (forceRefresh = false): Promise<LanguageCategory[]> => {
        // 如果已经加载过且不强制刷新，直接返回缓存数据
        if (languageCategoriesLoaded.value && !forceRefresh) {
            return languageCategories.value
        }

        // 如果正在加载中，等待加载完成
        if (languageCategoriesLoading.value) {
            return new Promise((resolve) => {
                const checkLoaded = () => {
                    if (languageCategoriesLoaded.value) {
                        resolve(languageCategories.value)
                    } else {
                        setTimeout(checkLoaded, 100)
                    }
                }
                checkLoaded()
            })
        }

        languageCategoriesLoading.value = true

        try {
            const response = await service.get('/lang/getAll')
            languageCategories.value = response?.data || []
            languageCategoriesLoaded.value = true
            return languageCategories.value
        } catch (error) {
            console.error('Error fetching language categories:', error)
            ElMessage.error('获取语言分类失败')
            return []
        } finally {
            languageCategoriesLoading.value = false
        }
    }

    // 清除缓存（用于数据更新后刷新）
    const clearCache = () => {
        articleCategoriesLoaded.value = false
        languageCategoriesLoaded.value = false
        articleCategories.value = []
        languageCategories.value = []
    }

    // 刷新所有数据
    const refreshAllData = async () => {
        clearCache()
        await Promise.all([
            getArticleCategories(true),
            getLanguageCategories(true)
        ])
    }

    return {
        // 状态
        articleCategories,
        languageCategories,
        articleCategoriesLoading,
        languageCategoriesLoading,
        articleCategoriesLoaded,
        languageCategoriesLoaded,

        // 方法
        getArticleCategories,
        getLanguageCategories,
        clearCache,
        refreshAllData,
        buildTree
    }
})

